package com.tebiecloud.ali.server.controller.feign;

import com.tebiecloud.ali.client.constants.ResultEnum;
import com.tebiecloud.ali.client.service.IAliOssClient;
import com.tebiecloud.ali.server.service.AliOssService;
import com.tebiecloud.common.model.ResultBody;
import com.tebiecloud.common.utils.DateUtils;
import com.tebiecloud.common.utils.ResultBodyUtils;
import com.tebiecloud.common.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

@RestController
@RequestMapping("/feign/oss")
public class AliUploadController implements IAliOssClient {

    @Autowired
    private AliOssService aliOssService;

    /**
     * 文件上传
     * @param type 图片类型：例如shop(门店图片) , bank(银行卡图片) ,user(店员头像) ,other(其它)
     * @param file
     * @return
     */
    @Override
    @PostMapping("uploadImage")
    public ResultBody uploadImage(@RequestParam("type") String type, @RequestParam("file") File file){
        String data = "";
        try {
            String filename = file.getName();
            String path = "tebie/" + type + "/image/" + DateUtils.formatCurrentDate("yyyyMMdd") + "/";
            String ossKey = path + UUIDUtil.get32UUID() + "." + filename.substring(filename.lastIndexOf(".") + 1);
            InputStream inputStream = new FileInputStream(file);
            data = aliOssService.upload(ossKey, inputStream);
        } catch (Exception e) {
            return ResultBodyUtils.failed(ResultEnum.ALI_IMAGE_UPLOAD_FAILED.getMessage());
        }
        return ResultBodyUtils.ok(data);
    }
}
